package com.example.receiver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.util.DataBuilder;

public class TcpReceiver {

	private final static Logger log = LoggerFactory.getLogger(TcpReceiver.class);
	
	protected Socket socket;

	protected String ip;
	
	protected int port;

	protected String md5;
	
	public TcpReceiver(String ip, int port, String md5) throws Exception {
		this.ip = ip;
		this.port = port;
		this.md5 = md5;
	}
	
	public void accept() throws Exception {
		socket = new Socket(ip, port);
		socket.setKeepAlive(false);
//		socket.
//		PrintWriter writer = new PrintWriter(socket.getOutputStream());
//		writer.println("file");
//		writer.flush();
		
		log.info("accepting file from server {}:{}", ip, port);
		
		new Thread(){
			@Override
			public void run() {
				try{
					BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
					String file = System.getProperty("user.home") + "/" + DateFormatUtils.format(new Date(), "yyyyMMdd-HHmmss");
					
					log.info("write file to {} ", file);
					BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
					
/*
					while((len = input.read(buffer)) != -1){
						byte[] data = new byte[len];
						if(len < buffer.length){
							// 文件结尾
							System.arraycopy(buffer, 0, data, 0, len);
						}else{
							data = buffer;
						}
						
						String s = new String(data, "UTF-8");
						System.out.println(s);
						FilePart part = DataBuilder.buildObject(Des.decryptDES(s, ClientConstants.key, ClientConstants.key), FilePart.class);
						
						output.write(part.data, 0, part.data.length);
					}
*/					
					byte[] buffer = new byte[512];
					int len = -1;
//					int md5Length = 32;
//					int md5Count = 0;
					
//					List<byte[]> md5Bytes = new ArrayList<>();
					
					while(input.available() > 0){
						len = input.read(buffer);
						byte[] data = buffer;
						
//						md5Count += len;
//						if(md5Count <= md5Length){
//							md5Bytes.add(data);
//						}
						
						if(len < buffer.length){
							// 文件结尾
							data = new byte[len];
							System.arraycopy(buffer, 0, data, 0, len);
						}
						
						output.write(data, 0, data.length);
						output.flush();
					}
					
					output.close();
					socket.close();
					
					log.info("received md5 is {}", md5);
					if(DataBuilder.buidMD5Checksum(new File(file)).equals(md5)){
						log.info("MD5 MATCHED!!");
					}else{
						log.info("MD5 NOT MATCHED!!");
					}
					
					log.info("receive file done!!");
				}catch(Exception e){
					log.error("failed to accept file", 2);
				}
			}
		}.start();;

	}
}
